// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()
const _ = db.command

const deliStts = {
  stts: {},
  shop: 'all',
  deli: '',
  delivery: [],
  order2shop: {},
  async doStts(start, end, shop, deli) {
    this.shop = shop
    this.deli = deli
    this.stts = this.order2shop = {}
    const orders = await deliStts.loadAllOrders(start, end)
    if (shop != 'all') {
      await this.mapOrder2Shop(orders)
    }
    await this.calculate(orders)
    this.postCalc()
    return this.stts
  },
  async calculate(orders) {
    for (const order of orders) {
      if (!this.matchOrder(order)) continue;
      this.totalDeli(order)
    };
  },
  async loadAllOrders(start, end) {
    const MAX_LIMIT = 100
    // 先取出集合记录总数
    const where = {
      payStatus: _.eq('success'),
      createTime: _.and(_.gte(start), _.lte(end))
    }
    const countResult = await db.collection('orders').where(where).count()
    const total = countResult.total
    // 计算需分几次取
    const batchTimes = Math.ceil(total / 100)
    // 承载所有读操作的 promise 的数组
    const tasks = []
    for (let i = 0; i < batchTimes; i++) {
      const promise = db.collection('orders').where(where).field({
        _id: true,
        _openid: true,
        createtime: true,
        status: true,
        totalFee: true,
        ticketOrderId: true,
        ticketInfo: true,
        refoundInfo: true,
        deliveryMan: true
      }).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
      tasks.push(promise)
    }
    // 等待所有
    return (await Promise.all(tasks)).reduce((acc, cur) => {
      return {
        data: acc.data.concat(cur.data),
        errMsg: acc.errMsg,
      }
    }).data
  },
  postCalc() {
    for (const key of Object.keys(this.stts)) {
      for (const skey of Object.keys(this.stts[key])) {
        const val = this.stts[key][skey]
        this.stts[key][skey] = this.readableNum(val)
      }
    }
  },
  readableNum(num) {
    const val = Number(num)
    if (val >= 10000) {
      return Number(val / 10000).toFixed(0) + '万零' + this.fixNum(val % 10000)
    }
    return this.fixNum(val)
  },
  fixNum(num) {
    return num.toFixed(0)
  },
  matchOrder(order) {
    if (order.ticketInfo) return false;
    // 已取消的订单deliveryMan可能空
    // console.log(this.deli, order.deliveryMan, order._id)
    let bshop = false,
      bdeli = false;
    if (this.shop == 'all') bshop = true;
    else bshop = (this.order2shop[order._openid] > 0);

    if (this.deli == 'all') bdeli = true;
    else bdeli = (order.deliveryMan == this.deli);

    return bshop && bdeli;
  },
  async mapOrder2Shop(orders) {
    const MAX_LIMIT = 100
    // 先取出集合记录总数
    const openids = []
    for (const o of orders) openids.push(o._openid)
    const where = {
      _openid: _.in(openids),
      shop: _.eq(String(this.shop))
    }
    const countResult = await db.collection('delivery_addr').where(where).count()
    const total = countResult.total
    console.log(total)
    if (total == 0) return {}

    // 计算需分几次取
    const batchTimes = Math.ceil(total / 100)
    // 承载所有读操作的 promise 的数组
    const tasks = []
    for (let i = 0; i < batchTimes; i++) {
      const promise = db.collection('delivery_addr').where(where).field({
        shop: true,
        _openid: true
      }).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
      tasks.push(promise)
    }
    // 等待所有
    const res = (await Promise.all(tasks)).reduce((acc, cur) => {
      return {
        data: acc.data.concat(cur.data),
        errMsg: acc.errMsg,
      }
    })

    for (const m of res.data) {
      this.order2shop[m._openid] = parseInt(m.shop)
    }
    console.log(this.order2shop)
    return this.order2shop
  },
  totalDeli(order) {
    if (order.ticketInfo) return
    // console.log(order)
    this.stts.total = this.stts.total || {
      total: 0,
      wait: 0,
      deli: 0,
      arr: 0,
      refound: 0,
      cancel: 0
    }
    const t = this.stts.total
    t.total += 1
    switch (order.status) {
      case '待配送':
        t.wait += 1;
        break;
      case '配送中':
        t.deli += 1;
        break;
      case '已送达':
        t.arr += 1;
        break;
      case '已退款':
        t.refound += 1;
        break;
      case '已取消':
        t.cancel += 1;
        break;
      default:
        console.log(order)
    }
  },
}
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const {
    start,
    end,
    shop,
    deli
  } = event
  const stts = await deliStts.doStts(start, end, shop, deli)
  return {
    stts
  }
}